import { Injectable } from "@nestjs/common";
import COS from "cos-nodejs-sdk-v5";
import config from "src/config"
import axios from "axios";
import { dateFormat, randomString } from "src/utils";
const COSClient = require('cos-nodejs-sdk-v5');
const mime = require('mime-kind');
@Injectable()
export class CosService {
	cos:COS
	constructor() {
		this.cos=new COSClient({
			SecretId: config.cos.SecretId,
			SecretKey: config.cos.SecretKey,
		})
	}

	/**从buffer上传文件 */
	async uploadFromBuffer(buffer:Buffer,path:string){
		return new Promise(async (resovle,reject)=>{
			this.cos.putObject({
				Bucket: config.cos.Bucket,
				Region: config.cos.Region,
				Key:path,
				Body:buffer
			}).then(cosRes=>{
				resovle('https://'+cosRes.Location)
			})
		})
	}

	/**从网络地址上传文件 */
	async uploadFromNetwork(url:string,folder:string):Promise<string>{
		return new Promise((resovle,reject)=>{
			axios.get(url,{responseType:"arraybuffer"}).then(async res=>{
				let buffer=res.data as Buffer
				let key=await this.createOssPath(buffer,folder)
				this.cos.putObject({
					Bucket: config.cos.Bucket,
					Region: config.cos.Region,
					Key:key,
					Body:buffer
				}).then(cosRes=>{
					resovle('https://'+cosRes.Location)
				})
			})
		})
	}

	async uploadFromBase64(base64:string,folder:string):Promise<string>{
		return new Promise(async (resovle,reject)=>{
			var buffer = Buffer.from(base64 , 'base64');
			let key=await this.createOssPath(buffer,folder)
			this.cos.putObject({
				Bucket: config.cos.Bucket,
				Region: config.cos.Region,
				Key:key,
				Body:buffer
			}).then(cosRes=>{
				resovle('https://'+cosRes.Location)
			})
		})
	}

	private async createOssPath(buffer:Buffer,folder, extraStr = '') {
		let year = dateFormat(new Date(), 'yyyy')
		let month = dateFormat(new Date(), 'MM')
		let day = dateFormat(new Date(), 'dd')
		if (extraStr) {
			extraStr += '_'
		}
		let name = `${year}/${month}/${day}/${extraStr}${randomString(32)}`

		let type = await mime(buffer)

		if (folder && folder.charAt(folder.length - 1) !== '/') {
			folder = folder + '/'
		}
		let fileName = `upload/${config.env}/${folder}/${name}.${type.ext}`

		return fileName
	}
}
